<?php

/**
 * 微信结构
 * zc
 * 2018年11月7日09:54:41
 */
class WeChat extends MY_Model
{
    function __construct()
    {
       parent::__construct();
       $this->load->model('Weixin/Member_model', 'member');
    }

    /**
     * snsapi_base 静默授权 获取用户openid   进入回调页
     */
    function login_base()
    {
        // $redirect_url = urlencode("http://".$_SERVER['SERVER_NAME'].'/Index.php/login_base');
        $redirect_url = urlencode("http://".$_SERVER['HTTP_HOST'].'/Weixin/Login/loginBaseBack');
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
        redirect($url);
    }

    /**
     * snapi_userinfo 获取用户基本信息  点击关注
     */
    function login_userInfo()
    {
        $redirect_url = urlencode("http://".$_SERVER['HTTP_HOST'].'/Weixin/Login/logiUserInfoBack');
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        redirect($url);
    }

    /**
     * 通过code换取网页授权  微信登录
     */
    function getLoginAccess_token($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=".$code."&grant_type=authorization_code";
        $data = Curl::_get($url);
        
        return $data;
    }

    /**
     * 获取用户信息
     */
    function getUserInfo($data)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['access_token']."&lang=zh_CN";
        $data = Curl::_get($url);
       
        return $data;
    }

    /**
     * 获取token
     */
    function getAccess_token()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
        $data = Curl::_get($url);

        $token = $this->hw_getRecord('token',array(), 'access_token, update_time');
        if (count($token) != 0) {
            $this->hw_Update('token',array('access_token'=>$data['access_token']),array());
        } else {
            $this->hw_Insert('token',array('access_token'=>$data['access_token']));
        }
       
        return $data['access_token'];
    }

    /**
     * 获取jsapi_ticket js临时票据
     */
    function getTicket()
    {
        $data = $this->hw_getRecord('token',array(), 'access_token, update_time');
        if (count($data) != 0 && (strtotime($data['update_time']) + 7000 > time()))
        {
            $access_token = $data['access_token'];
        } else {
            $access_token = $this->getAccess_token();
        }
        
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
        $data = Curl::_get($url);

        return $data['ticket'];
    }

    /**
     * 获取js配置文件
     */
    function getConfig($url)
    {
        $timestamp = time()."";
        $noncestr = $this->generateNonceStr();
        $jsapi_ticket = $this->getTicket();
        $url = $url;
        $signature = sha1("jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url");
        $data = array(
            'appId'     =>APPID,
            'timestamp' =>$timestamp,
            'nonceStr'  =>$noncestr,
            'signature' =>$signature
        );
        echo json_encode($data);
    }

    /**
     * 获取字符串
     */
    public function generateNonceStr($length=32){
		// 密码字符集，可任意添加你需要的字符
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
		$str ="";  
		for ( $i = 0; $i < $length; $i++ )  {  
			$str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
			//$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];  
		}  
		return $str;  
    }

    /**
	 * 
	 * 通过code从工作平台获取openid机器access_token
	 */
	public function GetOpenidFromMp($code)
	{
		$url = $this->__CreateOauthUrlForOpenid($code);

		//初始化curl
		$ch = curl_init();
		$curlVersion = curl_version();
		$ua = "WXPaySDK/3.0.9 (".PHP_OS.") PHP/".PHP_VERSION." CURL/".$curlVersion['version']." ".MERCHANTID;

		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, $ua);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

		$proxyHost = "0.0.0.0";
		$proxyPort = 0;
		$config->GetProxy($proxyHost, $proxyPort);
		if($proxyHost != "0.0.0.0" && $proxyPort != 0){
			curl_setopt($ch,CURLOPT_PROXY, $proxyHost);
			curl_setopt($ch,CURLOPT_PROXYPORT, $proxyPort);
		}
		//运行curl，结果以jason形式返回
		$res = curl_exec($ch);
		curl_close($ch);
		//取出openid
		$data = json_decode($res,true);
		$this->data = $data;
		$openid = $data['openid'];
		return $openid;
    }
    
    /**
	 * 构造获取open和access_toke的url地址
	 */
	private function __CreateOauthUrlForOpenid($code)
	{
		$urlObj["appid"] = APPID;
		$urlObj["secret"] = APPSECRET;
		$urlObj["code"] = $code;
		$urlObj["grant_type"] = "authorization_code";
		$bizString = $this->ToUrlParams($urlObj);
		return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
    
    /**
	 * 拼接签名字符串
	 */
	private function ToUrlParams($urlObj)
	{
		$buff = "";
		foreach ($urlObj as $k => $v)
		{
			if($k != "sign"){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
}